<template>
  <el-container class="main-layout">
    <!-- 사이드바 -->
    <el-aside :width="isCollapse ? '64px' : '250px'" class="sidebar">
      <div class="sidebar-header">
        <div class="logo" v-if="!isCollapse">
          <h2>관리자 센터</h2>
        </div>
        <div class="logo-mini" v-else>
          <span>관</span>
        </div>
      </div>

      <el-menu
        :default-active="currentRoute"
        :collapse="isCollapse"
        :unique-opened="true"
        router
        class="sidebar-menu"
      >
        <!-- 仅管理员可见：系统概要（合作伙伴不可见） -->
        <el-menu-item v-if="isAdmin" index="/dashboard">
          <el-icon><Monitor /></el-icon>
          <template #title>시스템 개요</template>
        </el-menu-item>

        <!-- 管理员、合作伙伴、推荐人都可见：资金管理 -->
        <el-sub-menu v-if="isAdmin || isPartner || isReferrer" index="financial">
          <template #title>
            <el-icon><Money /></el-icon>
            <span>자금 관리</span>
          </template>
          <el-menu-item index="/deposit-management">
            <el-icon><Top /></el-icon>
            <template #title>충전 관리</template>
          </el-menu-item>
          <el-menu-item index="/withdraw-management">
            <el-icon><Bottom /></el-icon>
            <template #title>출금 관리</template>
          </el-menu-item>
        </el-sub-menu>

        <!-- 推荐人和合作伙伴看到简单的会员列表菜单项 -->
        <el-menu-item v-if="isReferrer || isPartner" index="/member-login">
          <el-icon><User /></el-icon>
          <template #title>회원 목록</template>
        </el-menu-item>

        <!-- 仅管理员看到完整的会员管理菜单（合作伙伴不可见） -->
        <el-sub-menu v-if="isAdmin" index="member">
          <template #title>
            <el-icon><User /></el-icon>
            <span>회원 관리</span>
          </template>
          <el-menu-item index="/member-login">
            <el-icon><User /></el-icon>
            <template #title>회원 관리</template>
          </el-menu-item>
          <el-menu-item index="/join-inquiry">
            <el-icon><ChatLineSquare /></el-icon>
            <template #title>추천인 관리</template>
          </el-menu-item>
          <el-menu-item index="/referral-withdraw-management">
            <el-icon><Money /></el-icon>
            <template #title>추천인 수익 출금 관리</template>
          </el-menu-item>
        </el-sub-menu>

        <!-- 仅管理员可见：质押管理（合作伙伴不可见） -->
        <el-menu-item v-if="isAdmin" index="/staking-management">
          <el-icon><Coin /></el-icon>
          <template #title>스테이킹 본금 관리</template>
        </el-menu-item>

        <!-- 仅超级管理员可见：合作伙伴管理 -->
        <el-menu-item v-if="isSuperAdmin" index="/partner-management">
          <el-icon><UserFilled /></el-icon>
          <template #title>파트너 관리</template>
        </el-menu-item>

        <!-- 仅普通管理员可见：系统设置（合作伙伴不可见） -->
        <el-menu-item v-if="isNormalAdmin" index="/settings" @click="showDevelopingMessage">
          <el-icon><Setting /></el-icon>
          <template #title>시스템 설정</template>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 메인 영역 -->
    <el-container class="main-container">
      <!-- 상단 내비게이션 -->
      <el-header class="header">
        <div class="header-left">
          <el-button
            text
            @click="toggleSidebar"
            class="collapse-btn"
          >
            <el-icon size="20">
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-button>

          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item v-if="isNormalAdmin" :to="{ path: '/dashboard' }">홈</el-breadcrumb-item>
            <el-breadcrumb-item v-if="isReferrer || isPartner">회원 목록</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentPageTitle && (isNormalAdmin || (isPartner && currentRoute !== '/member-login'))">{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <el-dropdown @command="handleUserMenuCommand">
            <div class="user-info">
              <el-avatar :size="32" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ adminName || '관리자' }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">프로필</el-dropdown-item>
                <el-dropdown-item command="changePassword">비밀번호 변경</el-dropdown-item>
                <el-dropdown-item divided command="logout">로그아웃</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 메인 콘텐츠 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Monitor,
  Money,
  Top,
  Bottom,
  User,
  UserFilled,
  Setting,
  Expand,
  Fold,
  ArrowDown,
  ChatLineSquare,
  Coin
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const isCollapse = ref(false)
const adminName = ref('')
const userType = ref<'ADMIN' | 'USER'>('ADMIN')
const adminRole = ref('')

// 현재 라우트
const currentRoute = computed(() => route.path)

// 管理员인지 확인 (包括合作伙伴) - 用于菜单显示权限
const isAdmin = computed(() =>
  userType.value === 'ADMIN'
)

// 普通管理员인지 확인 (不包括合作伙伴) - 用于需要严格权限的操作
const isNormalAdmin = computed(() =>
  userType.value === 'ADMIN' &&
  (adminRole.value === 'SUPER_ADMIN' || adminRole.value === 'ADMIN' || adminRole.value === 'OPERATOR')
)

// 超级管理员인지 확인
const isSuperAdmin = computed(() => userType.value === 'ADMIN' && adminRole.value === 'SUPER_ADMIN')

// 合作伙伴인지 확인
const isPartner = computed(() => userType.value === 'ADMIN' && adminRole.value === 'PARTNER')

// 추천인(일般 사용자)인지 확인
const isReferrer = computed(() => userType.value === 'USER')

// 현재 페이지 제목
const currentPageTitle = computed(() => {
  const titleMap: Record<string, string> = {
    '/dashboard': '시스템 개요',
    '/deposit-management': '충전 관리',
    '/withdraw-management': '출금 관리',
    '/member-login': '회원 관리',
    '/join-inquiry': '추천인 관리',
    '/referral-withdraw-management': '추천인 수익 출금 관리',
    '/staking-management': '스테이킹 본금 관리',
    '/partner-management': '파트너 관리',
    '/settings': '시스템 설정'
  }
  return titleMap[route.path] || ''
})

// 사이드바 토글
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 개발 중 메시지 표시
const showDevelopingMessage = () => {
  ElMessage.info('기능을 개발 중입니다. 조금만 기다려 주세요.')
}

// 사용자 메뉴 동작
const handleUserMenuCommand = (command: string) => {
  switch (command) {
    case 'profile':
      ElMessage.info('프로필 기능은 준비 중입니다.')
      break
    case 'changePassword':
      ElMessage.info('비밀번호 변경 기능은 준비 중입니다.')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 로그아웃 처리
const handleLogout = () => {
  ElMessageBox.confirm(
    '로그아웃하시겠습니까?',
    '로그아웃 확인',
    {
      confirmButtonText: '확인',
      cancelButtonText: '취소',
      type: 'warning'
    }
  ).then(() => {
    // 모든 관련 정보 삭제
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_user')
    localStorage.removeItem('admin_user_type')
    ElMessage.success('로그아웃되었습니다.')
    router.push('/login')
  }).catch(() => {
    // 사용자 취소
  })
}

// 관리자 정보 로드
const loadAdminInfo = () => {
  try {
    const userInfo = localStorage.getItem('admin_user')
    const savedUserType = localStorage.getItem('admin_user_type')

    if (userInfo) {
      const user = JSON.parse(userInfo)
      adminName.value = user.name || '관리자'
      adminRole.value = user.role || ''
    } else {
      adminName.value = '관리자'
    }

    // 用户类型设置
    if (savedUserType === 'USER' || savedUserType === 'ADMIN') {
      userType.value = savedUserType as 'ADMIN' | 'USER'
    }
  } catch (error) {
    console.error('사용자 정보 로드 실패:', error)
    adminName.value = '관리자'
  }
}

onMounted(() => {
  loadAdminInfo()
})
</script>

<style scoped lang="scss">
.main-layout {
  height: 100vh;
}

.sidebar {
  background: #001529;
  transition: width 0.3s ease;

  .sidebar-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ffffff1a;

    .logo {
      h2 {
        color: white;
        font-size: 18px;
        font-weight: 600;
        margin: 0;
      }
    }

    .logo-mini {
      span {
        color: white;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .sidebar-menu {
    border: none;
    background: transparent;

    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      color: #ffffff99;

      &:hover {
        background-color: #1890ff !important;
        color: white;
      }
    }

    :deep(.el-menu-item.is-active) {
      background-color: #1890ff !important;
      color: white;
    }

    :deep(.el-sub-menu) {
      .el-menu-item {
        background-color: #000c17;

        &:hover {
          background-color: #1890ff !important;
        }

        &.is-active {
          background-color: #1890ff !important;
        }
      }
    }
  }
}

.main-container {
  display: flex;
  flex-direction: column;
}

.header {
  background: white;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 60px;

  .header-left {
    display: flex;
    align-items: center;

    .collapse-btn {
      margin-right: 16px;
      padding: 8px;

      &:hover {
        background-color: #f5f5f5;
      }
    }

    .breadcrumb {
      :deep(.el-breadcrumb__item) {
        .el-breadcrumb__inner {
          font-weight: 400;
          color: #666;

          &:hover {
            color: #1890ff;
          }
        }

        &:last-child {
          .el-breadcrumb__inner {
            color: #1890ff;
            font-weight: 500;
          }
        }
      }
    }
  }

  .header-right {
    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 6px;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #f5f5f5;
      }

      .user-avatar {
        margin-right: 8px;
      }

      .username {
        font-size: 14px;
        color: #333;
        margin-right: 8px;
      }

      .dropdown-icon {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.main-content {
  background: #f5f7fa;
  overflow-x: hidden;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    z-index: 1000;

    &.is-collapse {
      left: -250px;
    }
  }

  .main-container {
    margin-left: 0;
  }

  .header {
    .breadcrumb {
      display: none;
    }
  }
}
</style>
